# coding:utf-8
from flask.ext.wtf import Form
from flask.ext.pagedown.fields import PageDownField
from wtforms import TextAreaField, SubmitField, StringField, BooleanField, SelectField
from wtforms.validators import DataRequired, Length, Regexp, ValidationError, Email
from project.auth.models import *


class PostForm(Form):
    body = PageDownField('你此刻在想什么呢？', validators=[DataRequired()])
    submit = SubmitField('发表')


class EditProfileForm(Form):
    name = StringField('姓名', validators=[Length(0, 64)])
    location = StringField('地址', validators=[Length(0, 64)])
    about_me = TextAreaField('个人介绍')
    submit = SubmitField('修改')


class EditProfileAdminForm(Form):
    email = StringField('Email', validators=[DataRequired('邮箱不能为空'), Length(1, 64), Email()])
    username = StringField('用户名', validators=[DataRequired('用户名不能为空'), Length(1, 64),
                                              Regexp('^[A-Za-z][A-Za-z0-9_]*$', 0, '用户名必须由数字、字母、下划线组成，且必须字母开头')])
    confirmed = BooleanField('已认证')
    role = SelectField('权限', coerce=int)
    name = StringField('姓名', validators=[Length(0, 64)])
    location = StringField('地址', validators=[Length(0, 64)])
    about_me = TextAreaField('个人介绍')
    submit = SubmitField('修改')

    def __init__(self, user, *args, **kwargs):
        super(EditProfileAdminForm, self).__init__(*args, **kwargs)
        self.role.choices = [(role.id, role.name) for role in Role.query.order_by(Role.name).all()]
        self.user = user

    def validate_email(self, field):
        if field.data != self.user.email and User.query.filter_by(email=field.data).first():
            raise ValidationError('邮箱已经被注册')

    def validate_username(self, field):
        if field.data != self.user.username and User.query.filter_by(username=field.data).first():
            raise ValidationError('用户名已经被注册')
